#include "StateManager.h"
#include "GameState.h"
#include "State_Intro.h"

StateManager::StateManager(int width, int height, int bpp, std::string title) :
gameWindow(sf::VideoMode(width, height, bpp), title)
{

	m_states.push_back(IntroState::instance(getWindow(), *this));
}

StateManager::~StateManager()
{
	while (!m_states.empty())
	{
		popState();
	}
}

void StateManager::changeState(GameState* state)
{
	if (!m_states.empty())
	{
		m_states.back()->exit();
		m_states.pop_back();
	}
	m_states.push_back(state);
	m_states.back()->init();
}

void StateManager::pushState(GameState* state)
{
	if (!m_states.empty())
		m_states.back()->pause();
	m_states.push_back(state);
	m_states.back()->init();
}

void StateManager::popState()
{
	if (!m_states.empty())
	{
		m_states.back()->exit();
		m_states.pop_back();
	}

	if (!m_states.empty())
	{
		m_states.back()->resume();
	}
	else
		m_running = false;
}



void StateManager::getInput()
{
	m_states.back()->getInput(gameWindow);
}

void StateManager::update()
{
	m_states.back()->update(*this);
}

void StateManager::draw()
{
	if (gameWindow.isOpen())
		m_states.back()->draw(gameWindow);
	else
		quit();
}

void StateManager::regulateFPS()
{
	while (fpsClock.getElapsedTime().asSeconds() <= 0.05f)
	{
		sf::sleep(sf::seconds(0.01f));
	}
	fpsClock.restart();
}


sf::RenderWindow& StateManager::getWindow()
{
	return gameWindow;
}

bool StateManager::isOpen()
{
	return m_running;
}

void StateManager::quit()
{
	m_running = false;
}